package com.example.xxt.my1;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.lang.ref.PhantomReference;

public class MainActivity extends AppCompatActivity {
    private ImageView tu;
    private Button btn_next;
    private Handler handler;
    private final  int MSC_CHANGE_DOG=1000;
    private int[] stamp = {
            R.drawable.tu1,R.drawable.tu2,R.drawable.tu3,R.drawable.tu4
    };
    private int index = 0;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == MSC_CHANGE_DOG) {
                    index = (index + 1) % stamp.length;
                    tu.setImageResource(stamp[index]);
                    return true;
                }
                return false;
            }
        });

        tu = findViewById(R.id.img_tu);
        btn_next = findViewById(R.id.btn_next);
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message message = new Message();
                            message.what = MSC_CHANGE_DOG;
                            handler.sendMessage(message);

                            index = (index + 1) % stamp.length;
                            tu.setImageResource(stamp[index]);
                        }
                    }
                }).start();

            }

        });

    }
}